package com.qingsong.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.qingsong.dto.*;
import com.qingsong.entity.Report;
import com.qingsong.entity.User;
import com.qingsong.feign.UserFeign;
import com.qingsong.mapper.ReportMapper;
import com.qingsong.result.Result;
import com.qingsong.service.ReportService;
import com.qingsong.vo.ReportSimpleListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

import static com.qingsong.entity.table.ReportTableDef.REPORT;

/**
 * 举报表 服务层实现。
 *
 * @author qingsong
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "report")
public class ReportServiceImpl extends ServiceImpl<ReportMapper, Report>  implements ReportService{
    @Autowired
    private UserFeign userFeign;

    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(ReportInsertDTO dto) {
        // 组装 entity 实体类
        Report report = BeanUtil.copyProperties(dto, Report.class);
        User user = userFeign.select(dto.getFkUserId()).getData();
        if(ObjectUtil.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        report.setNickname(user.getNickname());
        report.setCreated(LocalDateTime.now());
        report.setUpdated(LocalDateTime.now());
        return mapper.insert(report) > 0;
    }

    @Cacheable(key = "#p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Report select(Long id) {
        RelationManager.addQueryRelations("episode");
        return mapper.selectOneWithRelationsById(id);
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<ReportSimpleListVO> simpleList() {
        return QueryChain.of(mapper)
                .withRelations()
                .listAs(ReportSimpleListVO.class);
    }

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Page<Report> page(ReportPageDTO dto) {
        QueryChain<Report> queryChain = QueryChain.of(mapper);
        // episodeId 条件
        Long episodeId = dto.getFkEpisodeId();
        if (ObjectUtil.isNotNull(episodeId)) {
            queryChain.where(REPORT.FK_EPISODE_ID.eq(episodeId));
        }
        // userId 条件
        Long userId = dto.getFkUserId();
        if (ObjectUtil.isNotNull(userId)) {
            queryChain.where(REPORT.FK_USER_ID.eq(userId));
        }
        return queryChain.withRelations().page(new Page<>(dto.getPageNum(), dto.getPageSize()));
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(ReportUpdateDTO dto) {
        // 组装 entity 实体类
        Report report = BeanUtil.copyProperties(dto, Report.class);
        Result<User> user = userFeign.select(dto.getFkUserId());
        if(ObjectUtil.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        report.setNickname(user.getData().getNickname());
        report.setUpdated(LocalDateTime.now());
        return UpdateChain.of(report).where(REPORT.ID.eq(report.getId())).update();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {
        return mapper.deleteById(id) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        return mapper.deleteBatchByIds(ids) > 0;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteByUserId(Long userId) {
        return UpdateChain.of(mapper)
                .where(REPORT.FK_USER_ID.eq(userId))
                .remove();
    }
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteByUserIds(List<Long> userIds){
        return UpdateChain.of(mapper)
                .where(REPORT.FK_USER_ID.in(userIds))
                .remove();
    }

}
